<?php
include("autenticacio.php");
include("funcions.php");
require_once('Database.class.php');
$db = Database::getInstance(); 
$db->getConnection();

$ok = upload();
if( $ok ){
	parserCSV();
}

function upload(){
	if( isset( $_FILES['csv']['size'] ) && ( $_FILES['csv']['size'] > 0 ) ) {
		$tmp_nom = $_FILES['csv']['tmp_name'];
		$nom = $_FILES['csv']['name'];
		$tamany = $_FILES['csv']['size'];
		$ruta_fitxer = "../uploads/".$nom;
		if( !move_uploaded_file( $tmp_nom, $ruta_fitxer) ) {
			return 0;
		}else{
			return 1;
		}
	}
}

function parserCSV(){
	$taula = $_POST['taula'];
	$nom = $_FILES['csv']['name'];
	$atributs = array();
	$querylog = "";
	$row = 1;
	$handle = fopen("../uploads/$nom", "r");
	$commit = "commit";
	mysql_query("begin");

	while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
		$num = count($data);
		if( $row == 1 ){
			$atributs = $data;
			$querylog .= "<p> <b>$num</b> atributs<br /></p>\n";
		}else{
			//DADES
			$query = "SELECT * FROM $taula WHERE ".$atributs[0]."=".$data[0];
			$result = mysql_query($query);
			if(!$result)
			{
				$querylog .= "<b>Rollback</b> SELECT<br />";
				$commit = "rollback";
			}else{
				$nbrows = mysql_num_rows($result);
				if($nbrows>0){
					//update
					$update = "";
					for ($c=0; $c < $num; $c++) {
						$update .= $atributs[$c]."='".$data[$c]."'";
						if($c != $num - 1 ) $update .= ",";
					}
					$query2 = "UPDATE $taula SET $update WHERE ".$atributs[0]."=".$data[0];
					if(!mysql_query($query2))
					{
						$querylog .= "<b>Rollback</b> UPDATE<br />";
						$commit = "rollback";
					}
					$querylog .= "<b>Actualitzant</b> fila $row<br />";
				}else{
					//insert
					$insert_atributs = "";
					$insert_valors = "";
					for ($c=0; $c < $num; $c++) {
						$insert_atributs .= $atributs[$c];
						if($c != $num - 1 ) $insert_atributs .= ",";
						$insert_valors .= "'".$data[$c]."'";
						if($c != $num - 1 ) $insert_valors .= ",";
					}
					$query2 = "INSERT INTO $taula ( $insert_atributs ) VALUES ( $insert_valors )";
					if(!mysql_query($query2))
					{
						$querylog .= "<b>Rollback</b> INSERT<br />";
						$commit = "rollback";
					}
					$querylog .= "<b>Afegint</b> nova entrada ($insert_atributs)<br />";
				}
			}
		}
		$row++;
	}
	if($commit == "rollback")
	{
		$querylog .= "ERROR IN TRANSACTION<br /><br />transaction rolled back<br /><br />";
		echo "{failure: true}";
	}else{
		echo "{success: true}";
	}
	mysql_query($commit);
	fclose($handle);
	@unlink("../uploads/$taula.csv");
}


include("desconnexio.php");

?>
